import sys
import os
import time
import base64
import cv2
import json
import shutil
import numpy as np
from tqdm import tqdm

def base64_encode_img(image_path):
    with open(image_path, 'rb') as fp:
        if sys.version > '3':
            img_b64encode = base64.b64encode(fp.read()).decode("utf-8")  # base64编码
        else:
            img_b64encode = base64.b64encode(fp.read())
    return img_b64encode

def base64_decode_img(img_b64encode):
    img_b64decode = base64.b64decode(img_b64encode.encode("utf-8"))  # base64解码
    img_array = np.fromstring(img_b64decode, np.uint8)  # 转换np序列
    img = cv2.imdecode(img_array, -1)  # 转换Opencv格式
    return img

def get_image_tag(image, host="http://172.30.12.84:7042/predict"):
    tag_list = []
    try:
        param = {
            "image_data": base64_encode_img(image)
        }
        req_json = json.dumps(param)
        req_post = req_json.encode('utf-8')
        headers = {'Content-Type': 'application/json'}
        t1 = time.time()
        if sys.version > '3':
            import urllib.request
            req = urllib.request.Request(url=host, headers=headers, data=req_post)
            res = urllib.request.urlopen(req, timeout=30)
        else:
            import requests
            res = requests.post(url=host, json=param)
        # res = requests.post(url=env[env_type]["host"], headers=headers, data=req_json)
        t2 = time.time()
        time_elapse = round(t2 - t1, 2)
        # print("time elapse: %s" % time_elapse)
        res = res.read().decode('utf-8')
        response = json.loads(res)
#         print(response)
        if response["status"] == "success":
            tag_list = response["data"]

        # return response
    except:
        import traceback
        traceback.print_exc()
    return tag_list
input_dir = "/Users/mhy/Downloads/pic"
out_dir = "/Users/mhy/Downloads/pic/images_out"
if not os.path.exists(out_dir):
    os.makedirs(out_dir)
for imagename in tqdm(os.listdir(input_dir)):
    basename, ext = os.path.splitext(imagename)
    image_path = os.path.join(input_dir, imagename)
    tag_list = get_image_tag(image_path)
    new_image_path = os.path.join(out_dir, "%s_%s.jpg" %(basename, ",".join(tag_list)))
    image = cv2.imread(image_path)
    cv2.imwrite(new_image_path, image)